package com.lcb.sentinel.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import com.lcb.sentinel.myhandler.CustomerBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handleException")
    public String byResource() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("message", "按资源限流OK");

        return jsonObject.toString();
    }

    public String handleException(BlockException exception) {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 444);
        jsonObject.put("message", exception.getClass().getCanonicalName() + "\t服务不可用");

        return jsonObject.toString();
    }

    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl1")
    public String byUrl() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("message", "按资源限流OK");

        return jsonObject.toString();
    }

    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException2")
    public String customerBlockHandler() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("message", "按自定义限流OK");

        return jsonObject.toString();
    }
}
